//
//  SISSJsonRequestNetworkingManager.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/24.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSJsonRequestNetworkingManager.h"

@implementation SISSJsonRequestNetworkingManager

+ (instancetype)sharedManager {
    static SISSJsonRequestNetworkingManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 实例化Manager
        instance = [[SISSJsonRequestNetworkingManager alloc]initWithBaseURL:[NSURL URLWithString:BASE_URL]];
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        instance.requestSerializer.timeoutInterval = 30;
        
    });
    if ([SISSUserAccount shared].access_token.length > 0) {
        [instance.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",[SISSUserAccount shared].token_type,[SISSUserAccount shared].access_token] forHTTPHeaderField:@"Authorization"];
    } else {
        [instance.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];
    }
    return instance;
}


- (void)GETWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure {
//    if ([URLString containsString:@"jytbusiness"]) {
//        [kJsonRequestNetworkingManager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//    } else {
//        [kJsonRequestNetworkingManager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//    }
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    
    [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * task, NSDictionary * responseObject) {
//        NSLog(@"%@",task.originalRequest.URL);
//        NSLog(@"%@",task.currentRequest.URL);
//        NSLog(@"%@",task.originalRequest.HTTPMethod);
//        NSLog(@"%@",task.currentRequest.HTTPMethod);
//        NSLog(@"%@",task.originalRequest.allHTTPHeaderFields);
//        NSLog(@"%@",task.currentRequest.allHTTPHeaderFields);
//        NSLog(@"%@",[[NSString alloc] initWithData:task.originalRequest.HTTPBody encoding:NSUTF8StringEncoding]);
//        NSLog(@"%@",((NSHTTPURLResponse *)task.response).allHeaderFields);
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)POSTWithURLString:(NSString *)URLString parameters:(id)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure {
//    if ([URLString containsString:@"jytbusiness"]) {
//        [kJsonRequestNetworkingManager setValue:[NSURL URLWithString:BRANCH_BASE_URL] forKey:@"baseURL"];
//    } else {
//        [kJsonRequestNetworkingManager setValue:[NSURL URLWithString:BASE_URL] forKey:@"baseURL"];
//    }
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    
    [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * task, NSDictionary * responseObject) {
        // AFN的回调,默认就是在主线程
       
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;
        [MBProgressHUD YYR_HideHUD:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)PUTWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    [self PUT:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

- (void)DELETEWithURLString:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }

    [self DELETE:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // AFN的回调,默认就是在主线程
        if (success) {
            success(responseObject);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [SISSPublicSingleton shared].isHud = NO;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}


- (void)uploadFilesWithURLStr:(NSString *)URLStr serverName:(NSString *)serverName imagesArray:(NSArray *)imagesArray parameters:(NSDictionary *)parameters success:(void (^)(id responseObject))successBlock failed:(void (^)(NSError * error))failedBlock {
    
    if (![SISSPublicSingleton shared].isHud) {
        [MBProgressHUD YYR_ShowHUD:YES];
        [SISSPublicSingleton shared].isHud = YES;
    }
    [[SISSJsonRequestNetworkingManager sharedManager] POST:URLStr parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSUInteger i = 0 ;
        
        // 上传图片时，为了用户体验或是考虑到性能需要进行压缩
        for (UIImage *image in imagesArray) {
            
            // 压缩图片，指定宽度
            //            UIImage *  resizedImage =  [UIImage imageCompressed:image withdefineWidth:width];
            NSData * imgData = UIImageJPEGRepresentation(image, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmssSSS";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            // 拼接文件路径
            NSString *format = [PublicUtil yyr_contentTypeForImageData:imgData];
            NSString *fileName = [NSString stringWithFormat:@"%@%zd.%@",str,i,format != nil ? format : @""];
            // 拼接Data
            [formData appendPartWithFileData:imgData name:serverName fileName:fileName mimeType:@"application/octet-stream"];
            i++;
            //            [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"picflie%ld",(long)i] fileName:@"image.png" mimeType:@" image/jpeg"];
            //            i--;
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"downLoadProcess = %@",uploadProgress);
        //        if (uploadProgress) {
        //
        //            upLoadProgress(uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        //        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"responseObject = %@",responseObject);
        if (successBlock) {
            
            successBlock(responseObject);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error = %@",error);
        if (failedBlock) {
            
            failedBlock(error);
        }
        [SISSPublicSingleton shared].isHud = YES;;
        [MBProgressHUD YYR_HideHUD:YES];
    }];
}

@end
